﻿/********************************************************************
	created:	2011/05/29
	created:	29:5:2011   21:26
	filename: 	D:\My Documents\Visual Studio 2010\Projects\IntranetMessagerClient\Client\MainWindow.cs
	file path:	D:\My Documents\Visual Studio 2010\Projects\IntranetMessagerClient\Client
	file base:	MainWindow
	file ext:	cs
	author:		
	
	purpose:	主窗口
*********************************************************************/
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using Client.Async_ServiceReference;
using CommonLibrary;

namespace Client
{
    public partial class MainWindow : Form
    {
        #region Delegates

        public delegate void SendDataDelegate(byte[] message);

        #endregion

        internal static ThisUser MainWindowThisUser;
        internal static CreateDuplexChannel<IServiceRepository> MainWindowChannel;

        internal static SendDataDelegate SendDataDelegateFunc;

        //when we need change some property in another thread, used this parameter;
        internal static SynchronizationContext SyncContext;

        internal static ClientChatForms ThisClientChatForm;
        internal static RegWindow ThisRegWindow;

        public MainWindow()
        {
            InitializeComponent();
            SyncContext = SynchronizationContext.Current;
            SendDataDelegateFunc = CommonFunctionClass.SendData;
            ThisClientChatForm = new ClientChatForms();
            MainWindowChannel = new CreateDuplexChannel<IServiceRepository>();
            MainWindowChannel.PropertyChanged += MainWindowChannelPropertyChanged;
        }

        private void MainWindowThisUserPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "MyName")
            {
                if (!userInfoLabel.InvokeRequired)
                    userInfoLabel.Text = @"昵称：" + MainWindowThisUser.MyName;
                else
                    SyncContext.Post(ar => userInfoLabel.Text = @"昵称：" + MainWindowThisUser.MyName, null);
            }
            if (e.PropertyName == "MyUid")
            {
                if (!UserIDlabel.InvokeRequired)
                    UserIDlabel.Text = @"您的ID：" + MainWindowThisUser.MyUid;
                else
                    SyncContext.Post(ar => UserIDlabel.Text = @"您的ID：" + MainWindowThisUser.MyUid, null);
            }
            if (e.PropertyName == "IsLogin")
            {
                if (!LoginStatelabel.InvokeRequired)
                {
                    if (MainWindowThisUser.IsLogin)
                    {
                        LoginStatelabel.Text = @"在线";
                        loginBtn.Text = @"注销";
                        loginBtn.Enabled = true;
                    }
                    else
                    {
                        LoginStatelabel.Text = @"请重新登录";
                        loginBtn.Enabled = true;
                    }
                }
                else
                {
                    SyncContext.Post(ar =>
                                         {
                                             if (MainWindowThisUser.IsLogin)
                                             {
                                                 LoginStatelabel.Text = @"在线";
                                                 loginBtn.Text = @"注销";
                                                 loginBtn.Enabled = true;
                                             }
                                             else
                                             {
                                                 LoginStatelabel.Text = @"请重新登录";
                                                 loginBtn.Enabled = true;
                                             }
                                         }, null);
                }
                if (MainWindowThisUser.IsLogin)
                {
                    MainWindowThisUser.BeginUpdateKey = true;
                }
            }
            if (e.PropertyName == "BeginUpdateKey")
            {
                if (MainWindowThisUser.BeginUpdateKey)
                {
                    var desKeyUpdateMessage = new Protocol.DesKeyUpdate
                                                  {
                                                      MyName = MainWindowThisUser.MyName,
                                                      MyUid = MainWindowThisUser.MyUid
                                                  };
                    byte[] messageSend = CommonFunctionClass.SealMessageToEnvelope(desKeyUpdateMessage,
                                                                                   desKeyUpdateMessage.MyUid, false,
                                                                                   false);
                    SendDataDelegateFunc.BeginInvoke(messageSend, null, null);
                    MainWindowThisUser.BeginUpdateKey = false;
                }
            }
            if (e.PropertyName == "GetUsersInfo")
            {
                if (MainWindowThisUser.GetUsersInfo)
                {
                    var getOnlineUsersMessage = new Protocol.GetOnlineUsers
                                                    {
                                                        MyName = MainWindowThisUser.MyName,
                                                        MyUid = MainWindowThisUser.MyUid
                                                    };
                    byte[] messageSend = CommonFunctionClass.SealMessageToEnvelope(getOnlineUsersMessage,
                                                                                   getOnlineUsersMessage.MyUid, true,
                                                                                   false);
                    SendDataDelegateFunc.BeginInvoke(messageSend, null, null);
                    MainWindowThisUser.BeginUpdateKey = false;
                }
            }
            if (e.PropertyName == "UsersInfos")
            {
                if (!listBoxUsersInfo.InvokeRequired)
                {
                    if (listBoxUsersInfo.Items.Count > 0)
                        listBoxUsersInfo.Items.Clear();
                    foreach (UserInfoClass userInfo in MainWindowThisUser.UsersInfos)
                    {
                        if (userInfo.UserId != MainWindowThisUser.MyUid)
                            listBoxUsersInfo.Items.Add(userInfo);
                    }
                }
                else
                {
                    SyncContext.Post(ar =>
                                         {
                                             if (listBoxUsersInfo.Items.Count > 0)
                                                 listBoxUsersInfo.Items.Clear();
                                             foreach (UserInfoClass userInfo in MainWindowThisUser.UsersInfos)
                                             {
                                                 if (userInfo.UserId != MainWindowThisUser.MyUid)
                                                     listBoxUsersInfo.Items.Add(userInfo);
                                             }
                                         }, null);
                }
            }
        }

        private void PopupLoginWindow()
        {
            MainWindowThisUser = new ThisUser {IsUpdateKey = false, BeginUpdateKey = false, GetUsersInfo = false};
            MainWindowThisUser.PropertyChanged += MainWindowThisUserPropertyChanged;

            var loginWindow = new LoginWindow();
            loginWindow.Show();
        }

        private void MainWindowChannelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IP")
            {
                serverInfoLabel.Text = String.Format("服务器地址：{0}{2}连接模式:{1}", MainWindowChannel.IpAddress,
                                                     MainWindowChannel.IsTcp ? "TCP" : "HTTP", Environment.NewLine);
            }
        }

        private void LoginBtnClick(object sender, EventArgs e)
        {
            if (MainWindowThisUser == null)
            {
                PopupLoginWindow();
                loginBtn.Enabled = false;
            }
            else
            {
                var signOutMessage = new Protocol.SignOut
                                         {
                                             MyName = MainWindowThisUser.MyName,
                                             MyUid = MainWindowThisUser.MyUid,
                                             SendTime = DateTime.Now
                                         };
                byte[] messageSend = CommonFunctionClass.SealMessageToEnvelope(signOutMessage, signOutMessage.MyUid,
                                                                               false,
                                                                               false);
                SendDataDelegateFunc(messageSend);
                MainWindowThisUser = null;
                loginBtn.Text = @"登陆";
                userInfoLabel.Text = @"请登录或注册";
                UserIDlabel.Text = @"请登录或注册";
                LoginStatelabel.Text = @"请登录或注册";
                foreach (object b in listBoxUsersInfo.Items)
                {
                    var userInfo = b as UserInfoClass;
                    if (userInfo != null)
                    {
                        ClientChatForm chatForm = ThisClientChatForm.GetClientChatForm(userInfo.UserId);
                        if (chatForm != null)
                            chatForm.Close();
                    }
                }
                if (ThisRegWindow != null)
                    ThisRegWindow.Close();
                ThisRegWindow = null;
                listBoxUsersInfo.Items.Clear();
                ThisClientChatForm.ClearAll();
            }
        }

        private void ListBoxUsersInfoDoubleClick(object sender, EventArgs e)
        {
            var chatUser = listBoxUsersInfo.SelectedItem as UserInfoClass;
            ClientChatForm chatForm;
            if (chatUser == null)
                return;
            if (ThisClientChatForm.GetClientChatForm(chatUser.UserId) == null)
            {
                NewChatForm(out chatForm, MainWindowThisUser.MyUid, chatUser.UserId, MainWindowThisUser.MyName,
                            chatUser.UserName);
            }
            else
            {
                chatForm = ThisClientChatForm.GetClientChatForm(chatUser.UserId);
                chatForm.Show();
            }
        }

        internal static void NewChatForm(out ClientChatForm chatForm, int myUid, int receiverUid, string myName,
                                         string receiverName)
        {
            chatForm = new ClientChatForm(myUid, receiverUid, myName, receiverName);
            ThisClientChatForm.AddClientChatForm(receiverUid, chatForm);
            ClientChatForm syChatForm = chatForm;
            SyncContext.Post(shoe => syChatForm.Show(), null);
        }

        private static void ButtonRegisterClick(object sender, EventArgs e)
        {
            ThisRegWindow = new RegWindow();
            ThisRegWindow.Show();
        }
    }
}